﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lyh.Train.Data;
using Lyh.Train.Service;

namespace Lyh.Train.UI
{
    public partial class TrainSearchForm : BaseForm
    {
        private ListBox lbSatations;
        private QueryEntity queryEntity;
        private List<QueryLeftNewDTOData> trainData = new List<QueryLeftNewDTOData>();

        public delegate void AddingTrainHandler(object sender, List<QueryLeftNewDTOData> data);
        public event AddingTrainHandler OnAddingTrain;

        public TrainSearchForm()
        {
            InitializeComponent();
            SetData();
        }

        private void SetData()
        {
            queryEntity = new QueryEntity
            {
                optionDates = new List<string>(),
                seatTypeList = new List<string>(),
                start_time_str = "00:00--24:00",
                trainClass = "QB#D#Z#T#K#QT#"
            };

            dtpFromDate.Value = DateTime.Now.AddDays(Context.BeforeDay);
        }

        private void StationTextChanged(object sender, EventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox == null) return;
            if (!Controls.Contains(lbSatations))
            {
                lbSatations = new ListBox
                {
                    Visible = false
                };
                lbSatations.Click += new EventHandler(lbSatations_Click);
                Controls.Add(lbSatations);
            }
            lbSatations.DataSource = null;
            textBox.Tag = null;
            var key = textBox.Text.Trim().ToLower();

            if (string.IsNullOrWhiteSpace(key)) return;
            var stationList = Context.Stations;
            var list = stationList.FindAll(p => p.ShortName.Contains(key) || p.ShortName1.Contains(key) || p.FullName.Contains(key) || p.Name.Contains(key));

            if (list.Count <= 0) return;
            lbSatations.DisplayMember = "Name";
            lbSatations.ValueMember = "Code";
            lbSatations.DataSource = list;
            var textBoxLocation = textBox.Location;
            lbSatations.Location = new Point(textBoxLocation.X, textBoxLocation.Y + textBox.Height);
            lbSatations.Width = textBox.Width;
            lbSatations.Show();
            lbSatations.Tag = sender;
            lbSatations.BringToFront();
        }

        private void SelectStation(object sender)
        {
            var textBox = sender as TextBox;
            if (textBox == null || lbSatations.SelectedValue == null) return;
            var name = lbSatations.Text;
            var code = lbSatations.SelectedValue.ToString();
            textBox.Text = name;
            textBox.Tag = code;

            if (textBox.Name == txtFrom.Name)
            {
                queryEntity.from_station_telecode = code;
                queryEntity.from_station_telecode_name = name;
                txtTo.Focus();
            }
            else
            {
                queryEntity.to_station_telecode = code;
                queryEntity.to_station_telecode_name = name;
                dtpFromDate.Focus();
            }
            lbSatations.Visible = false;
        }

        private void lbSatations_Click(object sender, EventArgs e)
        {
            var listBox = sender as ListBox;
            if (listBox == null) return;
            SelectStation(listBox.Tag);
        }

        private void StationKeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                if (lbSatations.SelectedIndex > 0)
                {
                    lbSatations.SelectedIndex--;
                }
            }
            if (e.KeyCode == Keys.Down)
            {
                if (lbSatations.SelectedIndex < lbSatations.Items.Count - 1)
                {
                    lbSatations.SelectedIndex++;
                }
            }
            if (e.KeyCode == Keys.Return)
            {
                SelectStation(sender);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var items = clbTrain.CheckedItems;
            if (items.Count < 1 || OnAddingTrain == null)
            {
                MessageBox.Show("请选择车次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult = DialogResult.OK;
            var trains = items.OfType<QueryLeftNewDTOData>().ToList();
            OnAddingTrain(this, trains);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            pbLoading.Visible = true;
            if(!bwQueryTrain.IsBusy)bwQueryTrain.RunWorkerAsync();
        }

        private void bwQueryTrain_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                queryEntity.optionDates.Clear();
                queryEntity.train_date = dtpFromDate.Value.ToString("yyyy-MM-dd");
                queryEntity.optionDates.Add(queryEntity.train_date);
                trainData = TicketHelper.GetLeftTicket(queryEntity);
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        private void bwQueryTrain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pbLoading.Visible = false;
            if (trainData.Count < 1)
            {
                Alert("没有查询到车次信息");
                return;
            }
            lblTotal.Text = string.Format("(共计{0}个车次)", trainData.Count);
            clbTrain.DataSource = trainData;
            clbTrain.ValueMember = "secretStr";
            clbTrain.DisplayMember = "secretStr";
            clbTrain.Format += new ListControlConvertEventHandler(clbTrain_Format);
        }

        void clbTrain_Format(object sender, ListControlConvertEventArgs e)
        {
            var data = e.ListItem as QueryLeftNewDTOData;
            if (data == null) return;
            var t = data.queryLeftNewDTO;
            e.Value = string.Format("{0}\t{1}({3})\t\t→\t{2}({4})\t\t{5}", t.station_train_code, t.from_station_name, t.to_station_name, t.start_time, t.arrive_time, t.lishi);
            cbCodes.Items.Add(t.station_train_code);
        }

        private void cbCodes_TextChanged(object sender, EventArgs e)
        {
            clbTrain.DataSource = trainData.Where(t => t.queryLeftNewDTO.station_train_code.Contains(cbCodes.Text.ToUpper())).ToList();
            clbTrain.ValueMember = "secretStr";
            clbTrain.DisplayMember = "secretStr";
        }

        private void lnkAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            for (var i = 0; i < clbTrain.Items.Count; i++)
            {
                clbTrain.SetItemChecked(i, true);
            }
        }

        private void lnkInvert_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            for (var i = 0; i < clbTrain.Items.Count; i++)
            {
                clbTrain.SetItemChecked(i, !clbTrain.GetItemChecked(i));
            }
        }

    }
}
